package com.cj.controller;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cj.model.Bonus;
import com.cj.model.Employee;
import com.cj.model.PostSalary;
import com.cj.model.SalaryRecord;
import com.cj.model.Timecard;
import com.cj.utils.CommonUtil;
import com.jfinal.core.Controller;
import com.jfinal.ext.render.excel.PoiRender;

public class SalaryRecordController extends Controller {
	
	public void index() {
		Employee employee = (Employee)getSession().getAttribute("employee");
		Integer empId = employee.getInt("empId");
		Integer isAdmin = employee.getInt("isAdmin");
		List<SalaryRecord> records = null;
		if(isAdmin == 1) {
			records = SalaryRecord.me.getAllSalaryRecords();
		} else {
			records = SalaryRecord.me.getSalaryRecordsByEmployee(empId);
		}
		 if(records != null && !records.isEmpty()) {
			 for (SalaryRecord salaryRecord : records) {
					salaryRecord.put("insurance", calInsurance(salaryRecord));
					salaryRecord.put("attendence", calAttendence(salaryRecord));
					salaryRecord.put("total", calTotalMoney(salaryRecord));
				}
		 }
		
		setAttr("records", records);
		render("salaryRecord.jsp");
	}
	
	private double calInsurance(SalaryRecord record) {
		if(record == null) return 0;
		return record.getDouble("medicareMoney") + record.getDouble("endowmentMoney") + record.getDouble("birthMoney")
				+ record.getDouble("housingMoney") + record.getDouble("unemploymentMoney") + record.getDouble("injuryMoney");
	}
	
	private double calAttendence(SalaryRecord record) {
		if(record == null) return 0;
		return record.getDouble("extraWorkMoney") + record.getDouble("travelMoney") + record.getDouble("leaveMoney")
				+ record.getDouble("neglectWorkMoney") + record.getDouble("lateMoney");
	}
	
	private double calTotalMoney(SalaryRecord record) {
		if(record == null) return 0;
		return record.getDouble("basicSalary") + record.getDouble("insurance") + record.getDouble("attendence")
				+ record.getDouble("bonus");
	}
	
	public void recordInfo() {
		Map<String, Object> jsonResult = new HashMap<>();
		Integer recordId = getParaToInt("id");
		SalaryRecord record = SalaryRecord.me.findById(recordId);
		if(record != null) {
			jsonResult.put("status", "success");
			jsonResult.put("record", record);
		} else {
			jsonResult.put("status", "fail");
		}
		renderJson("result", jsonResult);
	}
	
	public void calPre() {
		Calendar calendar = Calendar.getInstance();
		Integer year = calendar.get(Calendar.YEAR);
		Integer month = calendar.get(Calendar.MONTH);
		String time = year + "-" + (month + 1);
		List<SalaryRecord> records = SalaryRecord.me.getSalaryRecordByTime(time);
		for (SalaryRecord record : records) {
			record.put("insurance", calInsurance(record));
			record.put("attendence", calAttendence(record));
		}
		setAttr("recordTime", time);
		setAttr("records", records);
		render("calculatorSalary.jsp");
	}
	
	private String formateTime(String time) {
		String[] ss = time.split("-");
		int month = Integer.parseInt(ss[1]);
		return ss[0] + "-" + month;
	}
	
	public void calSalary() {
		String recordTime = getPara("recordTime");
		recordTime = formateTime(recordTime);
		List<Employee> employees = Employee.me.getAllEmployees();
		if(employees != null && !employees.isEmpty()) {
			for (Employee employee : employees) {
				Integer empId = employee.getInt("empId");
				Integer postId = employee.getInt("postId");
				PostSalary postSalary = PostSalary.me.getPostSalaryByPost(postId);
				SalaryRecord record = SalaryRecord.me.getSalaryRecordByEmpAndTime(recordTime, empId);
				System.out.println(record);
				if(record == null) {
					//add
					record = new SalaryRecord();
					record.set("empId", empId);
					record.set("recordTime", recordTime);
					record.set("payDate", new Date());
					calBasicSalary(record, postSalary);
					calWelfares(record,postSalary);
					calTimecards(record, empId, recordTime);
					calBonus(record, empId, recordTime);
					setTotalMoney(record);
					record.save();
				} else {
					//edit
					record.set("empId", empId);
					record.set("recordTime", recordTime);
					record.set("payDate", new Date());
					calBasicSalary(record, postSalary);
					calWelfares(record,postSalary);
					calTimecards(record, empId, recordTime);
					calBonus(record, empId, recordTime);
					setTotalMoney(record);
					record.update();
				}
			}
		}
		List<SalaryRecord> records = SalaryRecord.me.getSalaryRecordByTime(recordTime);
		for (SalaryRecord record : records) {
			record.put("insurance", calInsurance(record));
			record.put("attendence", calAttendence(record));
		}
		setAttr("recordTime", recordTime);
		setAttr("records", records);
		render("calculatorSalary.jsp");
	}
	
	private void setTotalMoney(SalaryRecord record) {
		double totalMoney = calInsurance(record) + calAttendence(record) + record.getDouble("basicSalary") + record.getDouble("bonus");
		record.set("totalMoney", totalMoney);
	}
	
	private void calBasicSalary(SalaryRecord record, PostSalary postSalary) {
		if (postSalary != null) {
			Double basicSalary = postSalary.getDouble("basicSalary");
			record.set("basicSalary", basicSalary);
		} else {
			Double basicSalary = CommonUtil.BASIC_SALARY;
			record.set("basicSalary", basicSalary);
		}
	}
	
	private void calWelfares(SalaryRecord record, PostSalary postSalary) {
		if (postSalary != null) {
			Double basicSalary = postSalary.getDouble("basicSalary");
			Double medicareMoney = basicSalary * postSalary.getDouble("medicareRate") / 100;
			record.set("medicareMoney", medicareMoney);
			Double endowmentMoney = basicSalary * postSalary.getDouble("endowmentRate") / 100;
			record.set("endowmentMoney", endowmentMoney);
			Double birthMoney = basicSalary * postSalary.getDouble("birthRate") / 100;
			record.set("birthMoney", birthMoney);
			Double housingMoney = basicSalary * postSalary.getDouble("housingRate") / 100;
			record.set("housingMoney", housingMoney);
			Double unemploymentMoney = basicSalary * postSalary.getDouble("unemploymentRate") / 100;
			record.set("unemploymentMoney", unemploymentMoney);
			Double injuryMoney = basicSalary * postSalary.getDouble("injuryRate") / 100;
			record.set("injuryMoney", injuryMoney);
		} else {
			Double basicSalary = CommonUtil.BASIC_SALARY;
			Double medicareMoney = basicSalary * CommonUtil.MEDICARE_RATE / 100;
			record.set("medicareMoney", medicareMoney);
			Double endowmentMoney = basicSalary * CommonUtil.ENDOWMENT_RATE / 100;
			record.set("endowmentMoney", endowmentMoney);
			Double birthMoney = basicSalary * CommonUtil.BIRTH_RATE / 100;
			record.set("birthMoney", birthMoney);
			Double housingMoney = basicSalary * CommonUtil.HOUSING_RATE / 100;
			record.set("housingMoney", housingMoney);
			Double unemploymentMoney = basicSalary * CommonUtil.UNEMPLOYMENT_RATE / 100;
			record.set("unemploymentMoney", unemploymentMoney);
			Double injuryMoney = basicSalary * CommonUtil.INJURY_RATE / 100;
			record.set("injuryMoney", injuryMoney);
		}
	}
	
	private void calTimecards(SalaryRecord record, Integer empId, String time) {
		double extraWorkMoney = 0d;
		double travelMoney = 0d;
		double leaveMoney = 0d;
		double neglectWorkMoney = 0d;
		double lateMoney = 0d;
		
		List<Timecard> timecards = Timecard.me.getTimecardsByTime(empId, time);
		if(timecards != null && !timecards.isEmpty()) {
			for (Timecard timecard : timecards) {
				String cardType = timecard.getStr("cardName");
				if("请假".equals(cardType)) {
					leaveMoney += timecard.getDouble("cardMoney");
				} else if ("出差".equals(cardType)) {
					travelMoney += timecard.getDouble("cardMoney");
				} else if ("迟到".equals(cardType)) {
					lateMoney += timecard.getDouble("cardMoney");
				} else if ("旷工".equals(cardType)) {
					neglectWorkMoney += timecard.getDouble("cardMoney");
				} else if ("加班".equals(cardType)) {
					extraWorkMoney += timecard.getDouble("cardMoney");
				}
			}
		}
		record.set("extraWorkMoney", extraWorkMoney);
		record.set("travelMoney", travelMoney);
		record.set("leaveMoney", leaveMoney);
		record.set("neglectWorkMoney", neglectWorkMoney);
		record.set("lateMoney", lateMoney);
	}
	
	private void calBonus(SalaryRecord record, Integer empId, String time) {
		double bonus = 0d;
		List<Bonus> bonuses = Bonus.me.getBonusByTime(empId, time);
		if(bonuses != null && !bonuses.isEmpty()) {
			for (Bonus b : bonuses) {
				bonus += b.getDouble("bonusMoney");
			}
		}
		record.set("bonus", bonus);
	}
	
	public void exportRecords() {
		Employee employee = (Employee)getSession().getAttribute("employee");
		Integer empId = employee.getInt("empId");
		Integer isAdmin = employee.getInt("isAdmin");
		List<SalaryRecord> records = null;
		if(isAdmin == 1) {
			records = SalaryRecord.me.getAllSalaryRecords();
		} else {
			records = SalaryRecord.me.getSalaryRecordsByEmployee(empId);
		}
		PoiRender excel = new PoiRender(records);
		String[] columns = {"recordId","recordTime","empNo","empName","basicSalary","endowmentMoney",
				"medicareMoney","unemploymentMoney","injuryMoney","birthMoney","housingMoney","extraWorkMoney",
				"travelMoney","leaveMoney","lateMoney","neglectWorkMoney","bonus","totalMoney"};
		String[] heades = {"编号","工资月份","员工编号","员工姓名","基本工资","养老保险","医疗保险","失业保险",
				"工伤保险","生育保险","住房公积金","加班工资","出差补贴","请假扣除","迟到罚金","旷工罚金","奖金","总金额"};
		String fileName = "";
		try {
			fileName = new String("工资记录".getBytes("gbk"),"iso8859-1") + ".xls";
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		render(excel.sheetName("所有").headers(heades).columns(columns).fileName(fileName));
	}
}
